package com.education.ai.controller;

import com.education.ai.context.AdminContext;
import com.education.ai.context.TeacherContext;
import com.education.ai.entity.Teacher;
import com.education.ai.exception.BusinessException;
import com.education.ai.model.dto.LoginRequest;
import com.education.ai.model.dto.ChangePasswordRequest;
import com.education.ai.model.dto.RegisterRequest;
import com.education.ai.model.dto.TeacherResponse;
import com.education.ai.model.dto.UserResponse;
import com.education.ai.model.dto.StudentResponse;
import com.education.ai.service.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:8080", "http://localhost:8081"}, allowCredentials = "true")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthService authService;
    
    /**
     * 教师注册
     */
    @PostMapping("/register/teacher")
    public ResponseEntity<?> registerTeacher(@Valid @RequestBody RegisterRequest registerRequest) {
        try {
            logger.info("接收到教师注册请求 - 姓名: {}, 手机: {}", 
                    registerRequest.getName(), registerRequest.getPhone());
            
            // 设置用户角色为教师
            registerRequest.setUserRole(1);
            TeacherResponse teacher = authService.registerTeacher(registerRequest);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "注册成功");
            result.put("teacher", teacher);
            
            // 记录日志
            logger.info("教师注册成功 - 工号: {}, 姓名: {}", teacher.getTeacherId(), teacher.getName());
            
            return ResponseEntity.ok(result);
        } catch (BusinessException be) {
            // 处理业务异常
            logger.warn("教师注册失败(业务异常) - {}", be.getMessage());
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", be.getMessage());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            // 处理系统异常
            logger.error("教师注册失败(系统异常) - {}", e.getMessage(), e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
            
            return ResponseEntity.status(500).body(result);
        }
    }
    
    /**
     * 学生注册
     */
    @PostMapping("/register/student")
    public ResponseEntity<?> registerStudent(@Valid @RequestBody RegisterRequest registerRequest) {
        try {
            logger.info("接收到学生注册请求 - 姓名: {}, 班级: {}", 
                    registerRequest.getName(), registerRequest.getClassName());
            
            // 设置用户角色为学生
            registerRequest.setUserRole(2);
            StudentResponse student = authService.registerStudent(registerRequest);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "注册成功");
            result.put("student", student);
            
            // 记录日志
            logger.info("学生注册成功 - 学号: {}, 姓名: {}, 班级: {}", 
                    student.getStudentId(), student.getName(), student.getClassName());
            
            return ResponseEntity.ok(result);
        } catch (BusinessException be) {
            // 处理业务异常
            logger.warn("学生注册失败(业务异常) - {}", be.getMessage());
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", be.getMessage());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            // 处理系统异常
            logger.error("学生注册失败(系统异常) - {}", e.getMessage(), e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
            
            return ResponseEntity.status(500).body(result);
        }
    }
    
    /**
     * 兼容旧接口的注册端点
     */
    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @RequestBody RegisterRequest registerRequest) {
        // 根据用户角色选择不同的注册方法
        if (registerRequest.getUserRole() != null && registerRequest.getUserRole() == 2) {
            return registerStudent(registerRequest);
        } else {
            return registerTeacher(registerRequest);
        }
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            // 记录登录请求
            String userType = loginRequest.getUserRole() == 1 ? "教师" : 
                             (loginRequest.getUserRole() == 2 ? "学生" : "管理员");
            logger.info("接收到{}登录请求 - ID: {}, 登录类型: {}", 
                    userType, loginRequest.getLoginId(), loginRequest.getLoginType());
            
            UserResponse user = authService.login(loginRequest);
        
        // 生成令牌
            String token = authService.generateToken(user.getUserId(), user.getUserRole());
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "登录成功");
            result.put("user", user);
        result.put("token", token);
        
        // 记录日志
            logger.info("生成登录令牌 - 用户ID: {}, 姓名: {}, 类型: {}", 
                    user.getUserId(), user.getName(), userType);
            
            return ResponseEntity.ok(result);
        } catch (BusinessException be) {
            // 处理业务异常
            logger.warn("登录失败(业务异常) - {}", be.getMessage());
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", be.getMessage());
        
        return ResponseEntity.ok(result);
        } catch (Exception e) {
            // 处理系统异常
            logger.error("登录失败(系统异常) - {}", e.getMessage(), e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
            
            return ResponseEntity.status(500).body(result);
        }
    }
    
    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public ResponseEntity<?> logout(@RequestHeader("Authorization") String token) {
        // 从token中提取用户ID
        String userId = authService.getUserIdFromToken(token);
        Integer userRole = authService.getUserRoleFromToken(token);
        
        if (userId != null) {
            authService.logout(userId);
            
            // 清除上下文相关处理已移至AuthService实现中
            
            // 记录日志
            String userType = userRole == 1 ? "教师" : 
                            (userRole == 2 ? "学生" : "管理员");
            logger.info("{}退出登录 - 用户ID: {}", userType, userId);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "已退出登录");
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    public ResponseEntity<?> changePassword(
            @Valid @RequestBody ChangePasswordRequest request,
            @RequestHeader("Authorization") String token) {

        // 从token中提取用户ID
        String userId = authService.getUserIdFromToken(token);
        Integer userRole = authService.getUserRoleFromToken(token);

        if (userId == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "您尚未登录或登录已过期");
            return ResponseEntity.status(401).body(error);
        }

        try {
            authService.changePassword(userId, request);
            
            // 记录日志
            String userType = userRole == 1 ? "教师" :
                            (userRole == 2 ? "学生" : "管理员");
            logger.info("{}修改密码成功 - 用户ID: {}", userType, userId);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "密码修改成功");

        return ResponseEntity.ok(result);
        } catch (BusinessException be) {
            // 处理业务异常
            logger.warn("密码修改失败(业务异常) - {}", be.getMessage());

            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", be.getMessage());

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            // 处理系统异常
            logger.error("密码修改失败(系统异常) - {}", e.getMessage(), e);

            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");

            return ResponseEntity.status(500).body(result);
        }
    }
    
    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/current-user")
    public ResponseEntity<?> getCurrentUser(@RequestHeader("Authorization") String token) {
        // 从token中提取用户信息
        String userId = authService.getUserIdFromToken(token);
        Integer userRole = authService.getUserRoleFromToken(token);
        
        if (userId == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "您尚未登录或登录已过期");
            return ResponseEntity.status(401).body(error);
        }
        
        // 根据用户角色获取不同的用户信息
        // 这里需要修改实现，暂时只支持教师
        if (userRole == 1) {
            TeacherResponse teacher = authService.getTeacherById(userId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("user", teacher);
            result.put("userRole", userRole);
        
            return ResponseEntity.ok(result);
        }
        
        // 其他用户类型的处理将在AuthService实现中添加
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "不支持的用户类型");
        
        return ResponseEntity.status(400).body(result);
    }
    
    /**
     * 获取当前登录教师信息
     */
    @GetMapping("/current-teacher")
    public ResponseEntity<?> getCurrentTeacher(@RequestHeader("Authorization") String token) {
        // 从token中提取用户信息
        String teacherId = authService.getUserIdFromToken(token);
        Integer userRole = authService.getUserRoleFromToken(token);
        
        if (teacherId == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "您尚未登录或登录已过期");
            return ResponseEntity.status(401).body(error);
        }
        
        // 确认是否为教师角色
        if (userRole != 1) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "当前登录用户不是教师");
            return ResponseEntity.status(403).body(error);
        }
        
        // 获取教师信息
        TeacherResponse teacher = authService.getTeacherById(teacherId);
        if (teacher == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "未找到教师信息");
            return ResponseEntity.status(404).body(error);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("teacher", teacher);
        
        logger.info("获取教师信息成功 - 教师ID: {}, 姓名: {}, 学科: {}", 
                teacher.getTeacherId(), teacher.getName(), teacher.getSubject());
        
        return ResponseEntity.ok(result);
    }
} 